import { Component, Vue, Watch } from 'vue-property-decorator'
import { debounce } from '@/assets/js/common.js'
import { debounceInterface } from '@/assets/js/public'
interface selectInterface {
  value: string,
  label: string
}
@Component({})
export default class extends Vue {
  state: string = ''
  // 省份组
  provinces: selectInterface[] = []
  cities: selectInterface[] = []
  // 选中的省份
  province: string = ''
  // 选中的城市
  city: string = ''
  // 全国的城市
  allCity: selectInterface[] = []
  // 输入回调
  querySearchAsync: debounceInterface = debounce(async (query: string, cb: any) => {
    if(this.allCity.length) {
      if(query === '') return cb(this.allCity.slice(0,15))
      return cb(this.allCity.filter(item => item.value.toLowerCase().indexOf(query.toLowerCase()) !== -1))
    }
    const {status, data} = await this.$axios.get('/geo/city')
    if(status === 200) {
      this.allCity = data.map((item: any) => {
        return {
          value: item.name,
          id: item.id
        }
      })
      cb(this.allCity.filter(item => item.value.toLowerCase().indexOf(query.toLowerCase()) === 0))
    }
  })
  // 选择回调
  handleSelect(item: any) {
    console.log(item)
    this.toIndex(item.value)
  }
  // 监听省份
  @Watch('province')
  async getCity(news: string) {
    const {status, data} = await this.$axios.get(`/geo/province/${news}`)
    if(status === 200) {
      this.cities = data.map((item: any) => {
        return {
          value: item.id,
          label: item.name
        }
      })
    }
  }
  @Watch('city')
  setCity(news: selectInterface) {
    this.toIndex(news.label)
  }

  toIndex(name: string) {
    if(name) {
      this.$store.dispatch('geo/setCity', name)
      this.$router.push('/')
    }
  }
  // 拿省份
  async mounted() {
    const {status, data} = await this.$axios.get('/geo/province')
    if(status === 200) {
      this.provinces = data.map((item: any) => {
        return {
          value: item.id,
          label: item.name
        }
      })
    }
  }
}
